import React,{Component} from 'react';
import { connect } from 'react-redux';
import { Card,Button,Table,message,Form,Modal,Switch,Image } from 'antd';
import dayjs from 'dayjs';
import { PlusCircleOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import {reqNoticeList,reqUpdateNoticeUseStatus,reqDeleteNotice} from '../../../api';
import { saveNoticeAction } from '../../../redux/action_creators/push_action';
import {PAGE_SIZE,IMAGE_URL} from '../../../config';
import './notice.less';
const {Item} =Form;

@connect(
    state=>({push:state.push}),
    {
        saveNoticeList:saveNoticeAction
    }
)
 class Notice extends Component {
    state={
        noticeList:[],//用户列表
        isLoading:true, //table是否显示加载动画
        useStatus:1,
        id:'',
        isVisible:false,
        img:'-1',
        title:'',
        detail:'',
        createTime:''
    }
    componentDidMount(){
        const {noticeList } = this.props.push;
        if(noticeList.length>0){
            // console.log(studentList);
            this.setState({
                noticeList,
                isLoading:false,
            })
        }else{
            this.getNoticeList()
        }
    }
    // 获取用户列表
    getNoticeList = async () => {
        let result = await reqNoticeList()
        const { code,data,msg} = result
       if(code === 200){
           if(data.length===0)  message.success(msg,1)
           this.setState({
            noticeList:data,
            isLoading:false,
        })
            //   把用户列表保存到redux中
              this.props.saveNoticeList(data)
        }else{
            message.error(msg,1)      
        } 
    }
    // 添加修改默认状态
    onChangeUseStatus=(status)=>{
        if(status) this.setState({useStatus:1})
        else this.setState({useStatus:0})
    }
    onChangeText=(a)=>{
        console.log(a);
    }
    // 删除公告信息
    getDelete = async (id) =>{
        let  result = await reqDeleteNotice(id)
        const { code,msg} = result
        if(code === 200){
            message.success('删除公告成功！',1)
            let noticeList = [...this.state.noticeList]
            let userIndex;
            noticeList.forEach((item,index)=> {
                if(item.id === parseInt(id)) userIndex=index
            });
            noticeList.splice(userIndex,1)
            this.props.saveNoticeList (noticeList)
            this.setState({noticeList})
        }else{
            message.error(msg,1)
        }
    }
    // 删除公告信息
    deleteNotice =  (id) => {
        let{ getDelete } = this
        Modal.confirm({
            icon: <ExclamationCircleOutlined/>,
            title:'删除公告',
            content:'你确定要删除本条公告吗？',
            okText:'确定',
            cancelText:'取消',
            onOk(){
                getDelete(id)
            },
            onCancel() {
            console.log('取消');
            },
        });
    }
      // 修改公告状态
      changeStatus=async(id,useStatus)=>{
        console.log(useStatus);
    let noticeList = [...this.state.noticeList]
            if(useStatus === 1) useStatus = 0
            else useStatus = 1
            let result =await reqUpdateNoticeUseStatus(id,useStatus)
            const { code,msg} = result
            if(code === 200){
                message.success('公告状态修改成功',1)
                noticeList = noticeList.map((item)=>{
                    if(item.id === id)     item.useStatus = useStatus
                    return item;
                })
                this.setState({noticeList})
                this.props.saveNoticeList(noticeList)
            }else{
                message.error(msg,1)
            }
    }
    // 展示弹窗
    showModel=(item)=>{
        let { img,title,detail,createTime,useStatus}={...item}
        if(img===undefined) img='-1' 
        this.setState({isVisible:true,img,title,detail,createTime,useStatus})
    }
    render(){
        const { noticeList,isVisible, img,title,detail,createTime } = this.state
          const columns = [
            { title: '标题',
            width:'50%',
              dataIndex: 'title',
              key: 'id',
            },
            { title: '发布时间',
                dataIndex: 'createTime',
                key: 'id',
                render:time=>dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            },
            { title: '是否启用',
                key: 'id',
                render:(item)=>{
                    return(
                        <div>
                            <Switch checkedChildren="已启用" unCheckedChildren="未启用" onClick={()=>this.changeStatus(item.id,item.useStatus)} defaultChecked={item.useStatus===1?true:false} />
                        </div>
                    )
                }
              },
            { title: '操作',
                key: 'id',
                align:'center',
                render:(item)=>{
                    return(
                        <div>
                            <Button type="link" onClick={()=>{this.showModel(item)}}>详情</Button>
                            <Button type="link" onClick={()=>{this.props.history.push({ pathname:`/training/admin/push/notice/update/${item.id}`,state:{noticeItem:item} })}}>修改</Button>
                            <Button type="link" onClick={()=>{this.deleteNotice(item.id)}}>删除</Button>
                        </div>
                    )
                }
            },
          ];
      
        return (
            <div>
                <Card
                    extra={
                        <Button type="primary"  onClick={()=>{this.props.history.push({ pathname:`/training/admin/push/notice/update`,state:{noticeItem:[]} })}}>
                        <PlusCircleOutlined/>添加公告</Button>
                    }
                >
                    <Table 
                        dataSource={noticeList} 
                        columns={columns}
                        bordered
                        rowKey='id'
                        pagination={{
                            pageSize:PAGE_SIZE,
                        }}
                        loading={this.state.isLoading} 
                    />
                </Card>
                <Modal
                    title="公告详情"
                    visible={isVisible}
                    onOk={()=>this.setState({isVisible:false})}
                    onCancel={()=>this.setState({isVisible:false})}
                    footer={null}
                    maskClosable={false}
                    width={700}
                    >
                        <Item>
                            <div><span className="notice-name">标题：</span><span style={{fontWeight:'bolder ',fontSize:'20px'}}>{title}</span></div>
                        </Item>
                        <Item>
                            <div><span className="notice-name">封面：</span><span>{img==='-1'||img===null?'':<Image  width={200} src={IMAGE_URL+img} />}</span></div>
                        </Item>
                        <Item>
                            <div><span className="notice-name">内容：</span><span dangerouslySetInnerHTML={{__html:detail}}></span></div>
                        </Item>
                        <Item>
                            <div><span className="notice-name">更新时间：</span><span>{createTime?dayjs(createTime).format('YYYY年MM月DD日 HH:mm:ss'):''}</span></div>
                        </Item>
                    </Modal>
            </div>
        );
    }
}
export default Notice;